package com.sgb.kjwl.view.ui.activity.material.hall;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentXufangFaqiBinding;
import com.sgb.kjwl.di.pick.DaggerPickFragComponent;
import com.sgb.kjwl.di.pick.PickFragModule;
import com.sgb.jicai.entity.CentralizedMiningEntity;
import com.swgk.core.view.entity.MenuEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.adapter.home.CentralizedMining2Adapter;
import com.sgb.kjwl.view.widget.PickAreaProCityPopWindow;
import com.sgb.link.view.widget.PickCityPopWindow;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 需求大厅--需方集采
 */
@Deprecated
public class XufangFaQiFragment extends AppLazyFragment {

    @Inject
    XufangFaQiModle viewModel;
    FragmentXufangFaqiBinding binding;
    private CentralizedMining2Adapter centralizedMiningAdapter;
    private String jicaiMethod = "0";
//    public static final String JICAI_METHOD = "JiCaiMethod";
    private int jicaiType = 1;
//    public static final String JICAI_TYPE = "JiCaiType";
    private String keyWords = "";

    private boolean isLastPage;
    private boolean isTop = true;
    private PickSelectEntity all;
    //集采状态筛选
    private PickCityPopWindow statusPopWindow;//集采状态弹窗
    private List<PickSelectEntity> statusDatas = new ArrayList<>();
    private String statusNo = ""; //状态
    //省市--一二级筛选
    private PickAreaProCityPopWindow addrPopWindow;//省市选择弹窗
    private boolean addrIsChange;
    private List<PickSelectEntity> provinceDatas = new ArrayList<>();//省份数据
    private List<PickSelectEntity> cityDatas = new ArrayList<>();
    private String proNo = "";      //省
    private String cityNo = "";    //地区
    //商品类型---一二级筛选
    private PickAreaProCityPopWindow productTypesPopWindow;
    private PickCityPopWindow pickTimePopWindow; //截止时间
    private List<PickSelectEntity> timeDatas = new ArrayList<>();
    //时间
    private String timeNo;
    private boolean typesIsChange;
    private List<PickSelectEntity> typesFirstDatas = new ArrayList<>();//省份数据
    private List<PickSelectEntity> typesSecondDatas = new ArrayList<>();
    private String firstTypeNo = "";
    private String secondTypeNo = "";
    public static final String FROM_WHERE="FROM_WHERE";

    /**
     *  jicaiMethod 集采方式（一级tab：0全部，1即报即采，2汇集采购,3企业专项,4集采锁价）
     *  jicaiType   集采类型（二级tab：0全部，1商品集采 2 机械集采 3 设备集采 4 劳务集采 5房产集采 6租赁集采）
     * @return
     */
    public static XufangFaQiFragment newInstance(String fromWhere) {
        XufangFaQiFragment fragment = new XufangFaQiFragment();
        Bundle bundle = new Bundle();
        bundle.putString(FROM_WHERE, fromWhere);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerPickFragComponent.builder()
                .appComponent(appComponent)
                .pickFragModule(new PickFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_xufang_faqi, container, false);
        if("1".equals(getArguments().get(FROM_WHERE))){
            binding.include.includeLayout.setVisibility(View.VISIBLE);
        }else{
            binding.include.includeLayout.setVisibility(View.GONE);
        }
        return binding.getRoot();
    }


    @Override
    protected void initView() {
        binding.tvAddr.setOnClickListener(this);
        binding.tvType.setOnClickListener(this);
        binding.tvStatus.setOnClickListener(this);
        binding.tvTime.setOnClickListener(this);
        binding.imgBackTop.setOnClickListener(this);
        binding.include.tvSearch.setOnClickListener(this);
        binding.include.tvSearchDelete.setOnClickListener(this);
        //当第一级菜单为汇集采购时，显示截止时间，其余都不显示
        if ("2".equals(jicaiMethod)) {
            binding.tvTime.setVisibility(View.VISIBLE);
        } else {
            binding.tvTime.setVisibility(View.GONE);
        }
        if (jicaiType == 0) {//二级tab全部时
            binding.tvType.setVisibility(View.GONE);
        } else {
            binding.tvType.setVisibility(View.VISIBLE);
            setJiCaiTypeSelectTextViewWords();
        }
        all = new PickSelectEntity();
        all.setNo("");
        all.setProjectscale("全部");

        if (centralizedMiningAdapter == null) {
            centralizedMiningAdapter = new CentralizedMining2Adapter(getActivity(), null);
        }
        centralizedMiningAdapter.setItemClickCallBack(new CentralizedMining2Adapter.ItemClickCallBack() {
            @Override
            public void onItemClick(CentralizedMiningEntity entity) {
                if (!ClickUtils.isDoubleClick()) {
                    viewModel.getH5Url(entity.getNo());
                }
            }
        });
        DividerItemDecoration divider = new DividerItemDecoration(this.getContext(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this.getContext(), R.drawable.shape_list_divide_factory_jc));
        binding.recyclerView.addItemDecoration(divider);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        //解决数据加载不完的问题
//        binding.recyclerView.setNestedScrollingEnabled(false);
        binding.recyclerView.setHasFixedSize(true);
        //解决数据加载完成后, 没有停留在顶部的问题
        binding.recyclerView.setFocusable(false);
        binding.recyclerView.setAdapter(centralizedMiningAdapter);
        binding.recyclerView.setLoadingMoreEnabled(false);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initFilterData();
            }

            @Override
            public void onLoadMore() {
                if (!isLastPage) {
                    viewModel.getJiCaiList(proNo, cityNo, jicaiMethod, jicaiType, statusNo, firstTypeNo, secondTypeNo, keyWords, timeNo, true);
                } else {
                    MToast.showToast(getActivity(), "没有更多数据了");
                }
            }
        });
        initPopWindow();
        binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (layoutManager.findFirstVisibleItemPosition() > 0) {
                    binding.imgBackTop.setVisibility(View.VISIBLE);
                } else {
                    binding.imgBackTop.setVisibility(View.GONE);
                }
            }
        });
        binding.imgBackTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.recyclerView.scrollToPosition(0);
            }
        });
    }

    private void initFilterData() {
        viewModel.getJiCaiList(proNo, cityNo, jicaiMethod, jicaiType, statusNo, firstTypeNo, secondTypeNo, keyWords, timeNo, false);
    }

    @Override
    protected void onLazyLoad() {
        getData();
    }

    private void getData() {

        //从接口获取筛选项内容
        viewModel.getProvinceData(); //省份
        viewModel.getStatusListByType(jicaiMethod); //获取集采状态（根据集采方式）
        viewModel.getTypeDatesList("0", jicaiType == 0 ? "" : String.valueOf(jicaiType));//商品类别
        //时间
        viewModel.getDateTimeList();
        //列表
        initFilterData();
    }

    @Override
    public void onMultiClick(View v) {
        switch (v.getId()) {
             case R.id.tv_search:
                if (!TextUtils.isEmpty(binding.include.etView.getText().toString())) {
                    keyWords = binding.include.etView.getText().toString();
                    initFilterData();
                }
                break;
            case R.id.tv_search_delete:
                binding.include.etView.setText("");
                keyWords = "";
                initFilterData();
                break;
            case R.id.tv_addr:
                if (!addrIsChange) {
                    if (!addrPopWindow.isShowing()) {
                        setTextViewBg(binding.tvAddr, R.drawable.search_bg, R.mipmap.ic_down_arrow_u, R.color.color_333333);
                    }
                } else {
                    if (!addrPopWindow.isShowing()) {
                        setTextViewBg(binding.tvAddr, R.drawable.search_new_blue_bg, R.mipmap.ic_up_arrow_blue, R.color.new_blue);
                    }
                }
                if (null != provinceDatas && provinceDatas.size() > 0) {
                    addrPopWindow.showPopwindow(binding.hsTop, 0, 0);
                    addrPopWindow.setData(provinceDatas);
                }
                break;
            case R.id.tv_type:
                if (!typesIsChange) {
                    if (!productTypesPopWindow.isShowing()) {
                        setTextViewBg(binding.tvType, R.drawable.search_bg, R.mipmap.ic_down_arrow_u, R.color.color_333333);
                    }
                } else {
                    if (!productTypesPopWindow.isShowing()) {
                        setTextViewBg(binding.tvType, R.drawable.search_new_blue_bg, R.mipmap.ic_up_arrow_blue, R.color.new_blue);
                    }
                }
                if (null != typesFirstDatas && typesFirstDatas.size() > 0) {
                    productTypesPopWindow.showPopwindow(binding.hsTop, 0, 0);
                    productTypesPopWindow.setData(typesFirstDatas);
                }
                break;
            case R.id.tv_status:
                if (null == statusNo || "".equals(statusNo)) {
                    setTextViewBg(binding.tvStatus, R.drawable.search_bg, R.mipmap.ic_down_arrow_u, R.color.color_333333);
                }
                showStatusPopWindow();
                break;
            case R.id.tv_time:
                if (null == statusNo || "".equals(statusNo)) {
                    setTextViewBg(binding.tvTime, R.drawable.search_bg, R.mipmap.ic_down_arrow_u, R.color.color_333333);
                }
                showTimePopWindow();
                break;
        }
    }

    //初始化各选择弹框
    private void initPopWindow() {
        // 集采状态
        statusPopWindow = new PickCityPopWindow(this.getContext());
        statusPopWindow.setBgView(binding.grayLayout);
        statusPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                statusNo = (String) key1;
                String name = (String) key2;
                if ("全部".equals(name)) {
                    if (!binding.tvStatus.getText().equals("集采状态"))
                        initFilterData();
                    binding.tvStatus.setText("集采状态");
                    setTextViewBg(binding.tvStatus, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
                } else {
                    binding.tvStatus.setText(name);
                    setTextViewBg(binding.tvStatus, R.drawable.search_new_blue_bg, R.mipmap.ic_up_arrow_blue, R.color.new_blue);
                    initFilterData();
                }
            }
        });
        statusPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (null == statusNo || "".equals(statusNo)) {
                    setTextViewBg(binding.tvStatus, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
                }
            }
        });
        //集采地区
        addrPopWindow = new PickAreaProCityPopWindow(getActivity());
        addrPopWindow.setSelectProClick(new PickAreaProCityPopWindow.ProSelectClickCallBack() {
            @Override
            public void refreshCityList(String no) {
                viewModel.getCityData(no);
            }
        });
        addrPopWindow.setOkSelectClickCallBack(new PickAreaProCityPopWindow.OKSelectClickCallBack() {

            @Override
            public void selectProCityOK(String proNoSelect, String proNameSelect, String cityNoSelect, String cityNameSelect) {
                proNo = proNoSelect;
                cityNo = cityNoSelect;
                initFilterData();
                setTextViewBg(binding.tvAddr, R.drawable.search_new_blue_bg, R.mipmap.ic_up_arrow_blue, R.color.new_blue);
                if (!cityNameSelect.equals("")) {
                    binding.tvAddr.setText((cityNameSelect));
                } else {
                    if (null != proNameSelect && !proNameSelect.equals("")) {
                        binding.tvAddr.setText((proNameSelect));
                    } else {
                        binding.tvAddr.setText("集采范围");
                        setTextViewBg(binding.tvAddr, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
                    }
                }
                addrIsChange = true;
            }
        });
        addrPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (addrIsChange && null != proNo && !proNo.equals("")) {
                    setTextViewBg(binding.tvAddr, R.drawable.search_new_blue_bg, R.mipmap.ic_up_arrow_blue, R.color.new_blue);
                } else {
                    setTextViewBg(binding.tvAddr, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
                }
            }
        });
        //商品类型
        productTypesPopWindow = new PickAreaProCityPopWindow(getActivity());
        productTypesPopWindow.setType(jicaiType);
        productTypesPopWindow.setSelectProClick(new PickAreaProCityPopWindow.ProSelectClickCallBack() {
            @Override
            public void refreshCityList(String no) {
                viewModel.getTypeDatesList(no, jicaiType == 0 ? "" : String.valueOf(jicaiType));
            }
        });
        productTypesPopWindow.setOkSelectClickCallBack(new PickAreaProCityPopWindow.OKSelectClickCallBack() {

            @Override
            public void selectProCityOK(String proNoSelect, String proNameSelect, String cityNoSelect, String cityNameSelect) {
                firstTypeNo = proNoSelect;
                secondTypeNo = cityNoSelect;
                initFilterData();
                setTextViewBg(binding.tvType, R.drawable.search_new_blue_bg, R.mipmap.ic_up_arrow_blue, R.color.new_blue);
                if (!cityNameSelect.equals("")) {
                    binding.tvType.setText((cityNameSelect));//子类没有全部
                } else {
                    if (proNameSelect.equals("全部") || proNoSelect.equals("") || null == proNoSelect) {
                        setJiCaiTypeSelectTextViewWords();
                        setTextViewBg(binding.tvType, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
                    } else {
                        binding.tvType.setText((proNameSelect));
                    }
                }
                typesIsChange = true;
            }
        });
        productTypesPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (typesIsChange && null != firstTypeNo && !firstTypeNo.equals("")) {
                    setTextViewBg(binding.tvType, R.drawable.search_new_blue_bg, R.mipmap.ic_up_arrow_blue, R.color.new_blue);
                } else {
                    setTextViewBg(binding.tvType, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
                }
            }
        });

        // 截止时间
        pickTimePopWindow = new PickCityPopWindow(this.getContext());
        pickTimePopWindow.setBgView(binding.grayLayout);
//        pickTimePopWindow.setOutsideTouchable(false);
//        pickTimePopWindow.setFocusable(false);
        pickTimePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                timeNo = (String) key1;
                String name = (String) key2;
                if ("全部".equals(name)) {
                    if (!binding.tvTime.getText().equals("截止时间"))
                        initFilterData();
                    binding.tvTime.setText("截止时间");
                    setTextViewBg(binding.tvTime, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
                } else {
                    binding.tvTime.setText(name);
                    setTextViewBg(binding.tvTime, R.drawable.search_new_blue_bg, R.mipmap.ic_up_arrow_blue, R.color.new_blue);
                    initFilterData();
                }
            }
        });
        pickTimePopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (null == timeNo || "".equals(timeNo)) {
                    setTextViewBg(binding.tvTime, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
                }
            }
        });
    }

    public void setJiCaiTypeSelectTextViewWords() {
        switch (jicaiType) {
            case 1:
                binding.tvType.setText("商品类型");
                break;
            case 2:
                binding.tvType.setText("机械类型");
                break;
            case 3:
                binding.tvType.setText("设备类型");
                break;
        }
    }

    public void showUrl(String url) {
        WebViewX5HostActivity.start(getActivity(), url);
    }

    public void showList(List<CentralizedMiningEntity> list, boolean isLastPage) {
        this.isLastPage = isLastPage;
        binding.recyclerView.refreshComplete();
        binding.recyclerView.loadMoreComplete();
        if (list.size() > 0) {
            centralizedMiningAdapter.setDatas(list);
            binding.emptyView.setVisibility(View.GONE);
        } else {
            centralizedMiningAdapter.setDatasMayNull(null);
            binding.emptyView.setVisibility(View.VISIBLE);
            binding.imgBackTop.setVisibility(View.GONE);
        }
        if (isLastPage) {
            binding.recyclerView.setLoadingMoreEnabled(false);
        } else {
            binding.recyclerView.setLoadingMoreEnabled(true);
        }
    }

    public void loadMore(List<CentralizedMiningEntity> list, boolean isLastPage) {
        this.isLastPage = isLastPage;
        binding.recyclerView.refreshComplete();
        if (list.size() != 0) {
            centralizedMiningAdapter.addDatas(list);
        }
        if (isLastPage) {
            binding.recyclerView.setLoadingMoreEnabled(false);
        } else {
            binding.recyclerView.setLoadingMoreEnabled(true);
        }
    }

    public void setProvinceDatas(List<PickSelectEntity> datas) {
        provinceDatas.clear();
        provinceDatas.addAll(datas);
    }

    public void setCityDatas(List<PickSelectEntity> datas) {
        cityDatas.clear();
        cityDatas.addAll(datas);
        addrPopWindow.setCityDatas(cityDatas);
    }

    public void setTypesFirstDatas(List<MenuEntity> data) {
        List<PickSelectEntity> types = new ArrayList<>();
        if (data != null) {
            for (MenuEntity entity : data) {
                PickSelectEntity pickSelectEntity = new PickSelectEntity();
                pickSelectEntity.setNo(entity.getId());
                pickSelectEntity.setProjectscale(entity.getName());
                types.add(pickSelectEntity);
            }
        }
        types.add(0, all);
        typesFirstDatas.clear();
        typesFirstDatas.addAll(types);
    }

    public void setTypesSecondDatas(List<MenuEntity> data) {
        List<PickSelectEntity> types = new ArrayList<>();
        if (data != null) {
            for (MenuEntity entity : data) {
                PickSelectEntity pickSelectEntity = new PickSelectEntity();
                pickSelectEntity.setNo(entity.getId());
                pickSelectEntity.setProjectscale(entity.getName());
                types.add(pickSelectEntity);
            }
        }
        typesSecondDatas.clear();
        typesSecondDatas.addAll(types);
        productTypesPopWindow.setCityDatas(typesSecondDatas);
    }

    public void setStatusDatas(List<PickSelectEntity> datas) {
        statusDatas.clear();
        datas.add(0, all);
        statusDatas.addAll(datas);
    }

    private void showStatusPopWindow() {
        statusPopWindow.showPopwindow(binding.tvStatus);
        statusPopWindow.setData(statusDatas);
    }

    public void setTimeDatas(List<PickSelectEntity> datas) {
        timeDatas.clear();
        datas.add(0, all);
        timeDatas.addAll(datas);
    }

    private void showTimePopWindow() {
        pickTimePopWindow.showPopwindow(binding.tvTime);
        pickTimePopWindow.setData(timeDatas);
    }

    private void setTextViewBg(TextView textView, int bg, int img, int textColor) {
        textView.setBackground(getResources().getDrawable(bg));
        Drawable drawable_n = getResources().getDrawable(img);
        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());  //此为必须写的
        textView.setCompoundDrawables(null, null, drawable_n, null);
        textView.setTextColor(getResources().getColor(textColor));
    }
}
